// pages/share/index.js
const utils = require('../../utils/util.js')
const app = getApp()
import Toast from '../../vant-weapp/dist/toast/toast'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: app.globalData.navHeight,
    designId:'',
    code:'',
    dataType:'',
    posterImage:'',
    imageUrl:'',
    cardImgUrl:"marketing/pgroup1/M00/28/E5/rB8MM2J50qKAdjWDAA2Ph9D9RCI382.jpg",
    shareName:null,
    otherUserId:'',
    routes:"",
    real:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // 分享者 的 电话号码,或者 openId 
    const { id, code,type, url, shareName, source,routes,real} = options
    this.data.routes=routes || null
    // this.data.real=real || null
    this.data.designId = id
    this.data.code = code
    this.data.dataType = type
    this.data.shareName = shareName
    this.setData({
      real:real||null
    })
    console.log(this.data.real)
    if(source === 'ads'){
      this.data.imageUrl = url
    }else{ // crm
      this.getShareInfo(id, type)
    }
    
    this.handlePosterImage()
  },
  
  getShareInfo:function(id,type){
    const params = {
      dsgnId:id,
      type:type
    }
    utils.$http(app.globalData.api.SelectDsgnImg, params, 'GET', true, 'JSON').then(({ success, data, msg }) => {
      if (success === 1) {
         this.data.imageUrl = data
      }
    })

  },

  posterTabChange: function (e) {
    const index = e.detail.index
    if (index === 1) {
     
    }
  },

  handlePosterImage: function () {
    const userInfo =  wx.getStorageSync("userInfo")
    const phone =  wx.getStorageSync("phone")

    const params = {
      width: '400',
      // page:'pages/index/index',
      page: this.data.routes?this.data.routes:'pages/Details/main/index', // 分享进入小程序的页面
      userName: userInfo == null ? '' : userInfo.unionId,
      userPhone: userInfo == null ? '' : userInfo.phone ? userInfo.phone : phone,
      userHead: userInfo == null ? '' : userInfo.headImg,
      userID: userInfo == null ? '' : userInfo.userName,
      dsgnId: this.data.designId,
      objType: 0,
      sharingParty: 'ads',
      code:this.data.code
    }
    utils.globalShowTip(true, '获取海报中...')
    let apis
    if(this.data.real==='real'){
      apis=app.globalData.api.getRealShareQrCode+'?'+'type'+'='+'A'
    }else if(this.data.real==='ground'){
      apis=app.globalData.api.getRealShareQrCode+'?'+'type'+'='+'B'
    }else{
      apis=app.globalData.api.ShareAppletCode
    }
      utils.$http(apis, params, 'POST', true, 'JSON', 'base64').then(res => {
      const posterImage = "data:image/jpeg;base64," + wx.arrayBufferToBase64(res)
      this.setData({
        posterImage
      })
    })
  },

  posterGoBack:function(){
 
    const currentPages = getCurrentPages()
    if (currentPages.length <= 1){
       wx.switchTab({
         url: '/pages/home/main/index',
       })
    }else{
      wx.navigateBack({
       })
    }
  },

  //保存到相册
  savePhotoLibaray: function () {
    const _this = this
    wx.getSetting({
      success(res) {
        console.log(res, res.authSetting['scope.writePhotosAlbum'])
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.openSetting({
            success(res1) {
              console.log("setting:",res1)
              _this.saveImageToAlbum()
            }
          })
        } else {
          _this.saveImageToAlbum()
        }
      }
    })
  },

  saveImageToAlbum() {
    Toast.loading({
      mask: true,
      duration: 0,
      message: '图片保存中....'
    });
    utils.base64src(this.data.posterImage, (imagePath) => {
      wx.saveImageToPhotosAlbum({
        filePath: imagePath,
        fail: (failData) => {
          Toast.success('保存图片失败')
        },
        success(result) {
          //已授权过可直接执行保存图片
          Toast.clear()
          Toast.success('保存图片成功')
        }
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  getShare: function () {
    const openId = wx.getStorageSync('openId')
    const params = {
      userId: openId,
      objId: this.data.designId,
      objType: this.data.dataType,
      sharePlatform: "小程序",
      platformId: 'wechat'
    }
    utils.$http(app.globalData.api.Share, params, 'POST', false, "JSON").then((res) => {

    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const _this = this
    let dataType = this.data.dataType
    // let designId = this.data.code
    let designId = this.data.designId
    const sharerPhone = wx.getStorageSync('phone') || ''
    const sharerOpenId = wx.getStorageSync('openId') 
    
    // this.getShare()
    const urls=this.data.routes?this.data.routes+'?id=':"pages/Details/main/index?id="
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: this.data.shareName || '详情页',
        imageUrl: this.data.imageUrl,
        path: urls + designId + "&sharerPhone=" + sharerPhone + "&sharerOpenId=" + sharerOpenId
      }
    }
    return {
      title: this.data.shareName || '详情页',
      imageUrl: this.data.imageUrl,
      path: urls + designId + "&sharerPhone=" + sharerPhone + "&sharerOpenId=" + sharerOpenId
    }
  }
})
